//
//  UIImageView+SDImgView.m
//  DoulinClient
//
//  Created by YLKJ on 2019/1/22.
//

#import "UIImageView+SDImgView.h"
#import "HYBImageCliped.h"

#define kSD 0
#define kAF 0

//SDWebImageRetryFailed ：下载失败后,会重新下载
//SDWebImageLowPriority ：在用户正在进行用户操作的时候，SDWebImage停止下载图片

@implementation UIImageView (SDImgView)

#pragma mark - ------------------ <#note#> ------------------
static const char * urlKey = "imgURL";
- (void)setImgURL:(NSString *)imgURL {
    objc_setAssociatedObject(self, urlKey, imgURL, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSString *)imgURL {
    return objc_getAssociatedObject(self, urlKey);
}
static const char * thumbKey = "thumbKey";
- (void)setImgThumbURL:(NSString *)imgThumbURL {
    objc_setAssociatedObject(self, thumbKey, imgThumbURL, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSString *)imgThumbURL {
    return objc_getAssociatedObject(self, thumbKey);
}

#pragma mark ------------------- <#note#> ------------------
/** 压缩头像图片
 * url: NSString/NSUrl 对象
 * phImg: 占位图 默认:kIconPH
 * size: 目标尺寸(单倍图宽高)(根据size的长宽最小值将图片等比压缩) 默认:CGSizeMake(50, 50)
 */
- (void)yl_setIconWithUrl:(id)url {
    [self yl_setImgWithURL:url phImg:kIconPH size:CGSizeMake(50, 50)];
}
- (void)yl_setIconWithUrl:(id)url size:(CGSize)size {
    [self yl_setImgWithURL:url phImg:kIconPH size:size];
}
- (void)yl_setIconWithUrl:(id)url phImg:(UIImage *)phImg {
    [self yl_setImgWithURL:url phImg:phImg size:CGSizeMake(50, 50)];
}
- (void)yl_setIconWithUrl:(id)url phImg:(UIImage *)phImg size:(CGSize)size {
    NSURL * imgUrl;
    if ([url isKindOfClass:NSURL.class]) {
        imgUrl = url;
    }else if ([url isKindOfClass:NSString.class]) {
        imgUrl = [url toUrl];
    }
    self.imgURL = imgUrl.absoluteString;
#if kSD
    [self sd_setImageWithURL:imgUrl placeholderImage:phImg?phImg:kImgPH];
#elif kAF
    kWeak;
    NSURLRequest * req = [NSURLRequest requestWithURL:imgUrl];
    [self setImageWithURLRequest:req placeholderImage:phImg?phImg:kImgPH success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
        kStrong;
        self.image = image;
    } failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
        NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, error.localizedDescription);
    }];
#else
    //缩略图缓存(没有缩略图缓存时, 一定没有原图缓存)
    self.imgThumbURL = [NSString stringWithFormat:@"%@&thumbnail%d", imgUrl.absoluteString, (int)floor(MIN(size.width, size.height))];
    WeakSelf(self);
    // 异步读取图片，先从缓存读取，若没有读取到则从文件读取。若都没有取到，则走网络
    [HYBImageClipedManager clipedImageFromDiskWithKey:self.imgThumbURL completion:^(UIImage *image) {
        StrongSelf(self);
        if (image) {
            self.image = image;
        } else {
            SDWebImageOptions options = SDWebImageRetryFailed | SDWebImageLowPriority;// | SDWebImageAvoidAutoSetImage;
            [self sd_setImageWithURL:imgUrl placeholderImage:phImg?phImg:kImgPH options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                StrongSelf(self);
                if ((image == nil) || (error != nil)) {
                    return;
                }
                //NSLog(@"<-- %s, %d --> 🐔🐔🐔%@🐔🐔🐔", __FUNCTION__, __LINE__, NSStringFromCGSize(image.size));
                //NSLog(@"<-- %s, %d --> 🐔🐔%@🐔🐔", __FUNCTION__, __LINE__, NSStringFromCGSize(size));
                //下面这种方式会更好，可以解决滚动过快时，防止再赋值。其已经再次被复用时，不应该再赋值了
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                    StrongSelf(self);
                    CGFloat whMin = MIN(size.width, size.height);
                    CGSize resultSize = CGSizeZero;
                    if (image.size.width >= image.size.height) {
                        CGFloat scale = image.size.height / whMin;
                        CGFloat sizeW = image.size.width / scale;
                        resultSize = CGSizeMake(sizeW, whMin);
                    } else {
                        CGFloat scale = image.size.width / whMin;
                        CGFloat sizeH = image.size.height / scale;
                        resultSize = CGSizeMake(whMin, sizeH);
                    }
                    //NSLog(@"<-- %s, %d --> 🐔%@🐔", __FUNCTION__, __LINE__, NSStringFromCGSize(resultSize));
                    @autoreleasepool {
                        // 将剪裁后的图片记录下来，下次直接使用
                        CGSize resultS = CGSizeMake(kImgScale(resultSize.width) * 0.9, kImgScale(resultSize.height) * 0.9);
                        UIImage * clipeImg = [image hyb_clipToSize:resultS isEqualScale:NO];
                        // 存储到本地，若开启了缓存到内存，则也一起缓存内存，以提高性能
                        NSString *cacheKey = [NSString stringWithFormat:@"%@&thumbnail%d", imageURL.absoluteString, (int)floor(MIN(size.width, size.height))];
                        [HYBImageClipedManager storeClipedImage:clipeImg toDiskWithKey:cacheKey];
                        
                        #if 1   // 返回主线程显示图片
                        dispatch_async(dispatch_get_main_queue(), ^{
                            StrongSelf(self);
                            if ([[[self.imgThumbURL componentsSeparatedByString:@"&thumbnail"] safeObjectAtIndex:0] isEqualToString:imageURL.absoluteString]) {
                                self.image = clipeImg;
                            } else {
                                self.image = kIconPH;
                            }
                        });
                        #endif
                        
                    }
                });
            }];
        }
    }];
#endif
}

#pragma mark - ------------------ <#note#> ------------------
/** 压缩图片
 * url: NSString/NSUrl 对象
 * phImg: 占位图 默认:kImgPH
 * size: 目标尺寸(单倍图宽高)(根据size的长宽最小值将图片等比压缩)
 */
- (void)yl_setImgWithURL:(id)url size:(CGSize)size {
    [self yl_setImgWithURL:url phImg:kImgPH size:size];
}
- (void)yl_setImgWithURL:(id)url phImg:(UIImage *)phImg size:(CGSize)size {
    NSURL * imgUrl;
    if ([url isKindOfClass:NSURL.class]) {
        imgUrl = url;
    }else if ([url isKindOfClass:NSString.class]) {
        imgUrl = [url toUrl];
    }
    self.imgURL = imgUrl.absoluteString;
#if kSD
    [self sd_setImageWithURL:imgUrl placeholderImage:phImg?phImg:kImgPH];
#elif kAF
    kWeak;
    NSURLRequest * req = [NSURLRequest requestWithURL:imgUrl];
    [self setImageWithURLRequest:req placeholderImage:phImg?phImg:kImgPH success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
        kStrong;
        self.image = image;
    } failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
        NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, error.localizedDescription);
    }];
#else
    //缩略图缓存(没有缩略图缓存时, 一定没有原图缓存)
    self.imgThumbURL = [NSString stringWithFormat:@"%@&thumbnail%d", imgUrl.absoluteString,(int)floor(MIN(size.width, size.height))];
    WeakSelf(self);
    // 异步读取图片，先从缓存读取，若没有读取到则从文件读取。若都没有取到，则走网络
    [HYBImageClipedManager clipedImageFromDiskWithKey:self.imgThumbURL completion:^(UIImage *image) {
        StrongSelf(self);
        if (image) {
            self.image = image;
        } else {
            SDWebImageOptions options = SDWebImageRetryFailed | SDWebImageLowPriority;// | SDWebImageAvoidAutoSetImage;
            [self sd_setImageWithURL:imgUrl placeholderImage:phImg?phImg:phImg?phImg:kImgPH options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                StrongSelf(self);
                if ((image == nil) || (error != nil)) {
                    return;
                }
                //NSLog(@"<-- %s, %d --> 🐔🐔🐔%@🐔🐔🐔", __FUNCTION__, __LINE__, NSStringFromCGSize(image.size));
                //NSLog(@"<-- %s, %d --> 🐔🐔%@🐔🐔", __FUNCTION__, __LINE__, NSStringFromCGSize(size));
                //下面这种方式会更好，可以解决滚动过快时，防止再赋值。其已经再次被复用时，不应该再赋值了
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                    StrongSelf(self);
                    CGFloat whMin = MIN(size.width, size.height);
                    CGSize resultSize = CGSizeZero;
                    if (image.size.width >= image.size.height) {
                        CGFloat scale = image.size.height / whMin;
                        CGFloat sizeW = image.size.width / scale;
                        resultSize = CGSizeMake(sizeW, whMin);
                    } else {
                        CGFloat scale = image.size.width / whMin;
                        CGFloat sizeH = image.size.height / scale;
                        resultSize = CGSizeMake(whMin, sizeH);
                    }
                    //NSLog(@"<-- %s, %d --> 🐔%@🐔", __FUNCTION__, __LINE__, NSStringFromCGSize(resultSize));
                    @autoreleasepool {
                        // 将剪裁后的图片记录下来，下次直接使用
                        //CGSize resultS = CGSizeMake(kImgScale(resultSize.width), kImgScale(resultSize.height));
                        UIImage *clipeImg = [image hyb_clipToSize:resultSize isEqualScale:NO];
                        // 存储到本地，若开启了缓存到内存，则也一起缓存内存，以提高性能
                        NSString *cacheKey = [NSString stringWithFormat:@"%@&thumbnail%d", imageURL.absoluteString, (int)floor(MIN(size.width, size.height))];
                        [HYBImageClipedManager storeClipedImage:clipeImg toDiskWithKey:cacheKey];
                        
                        #if 1   // 返回主线程显示图片
                        dispatch_async(dispatch_get_main_queue(), ^{
                            StrongSelf(self);
                            if ([[[self.imgThumbURL componentsSeparatedByString:@"&thumbnail"] safeObjectAtIndex:0] isEqualToString:imageURL.absoluteString]) {
                                self.image = clipeImg;
                            } else {
                                self.image = kImgPH;
                            }
                        });
                        #endif
                        
                    }
                });
            }];
        }
    }];
#endif
}

#pragma mark - ------------------ <#note#> ------------------
/** 压缩正方形图片:(已知:所有商品图片/小区店铺icon)
 * url: NSString/NSUrl 对象
 * phImg: 占位图 默认:kImgPH
 * wh: 目标尺寸宽高(单倍图宽高)
 */
- (void)yl_setSquareImgWithURL:(id)url wh:(CGFloat)wh {
    [self yl_setSquareImgWithURL:url phImg:kImgPH wh:wh];
}
- (void)yl_setSquareImgWithURL:(id)url phImg:(UIImage *)phImg wh:(CGFloat)wh {
    NSURL * imgUrl;
    if ([url isKindOfClass:NSURL.class]) {
        imgUrl = url;
    }else if ([url isKindOfClass:NSString.class]) {
        imgUrl = [url toUrl];
    }
    self.imgURL = imgUrl.absoluteString;
#if kSD
    [self sd_setImageWithURL:imgUrl placeholderImage:phImg?phImg:kImgPH];
#elif kAF
    kWeak;
    NSURLRequest * req = [NSURLRequest requestWithURL:imgUrl];
    [self setImageWithURLRequest:req placeholderImage:phImg?phImg:kImgPH success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
        kStrong;
        self.image = image;
    } failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
        NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, error.localizedDescription);
    }];
#else
    //缩略图缓存(没有缩略图缓存时, 一定没有原图缓存)
    self.imgThumbURL = [NSString stringWithFormat:@"%@&thumbnail%d", imgUrl.absoluteString, (int)wh];
    WeakSelf(self);
    // 异步读取图片，先从缓存读取，若没有读取到则从文件读取。若都没有取到，则走网络
    [HYBImageClipedManager clipedImageFromDiskWithKey:self.imgThumbURL completion:^(UIImage *image) {
        StrongSelf(self);
        if (image) {
            self.image = image;
        } else {
            SDWebImageOptions options = SDWebImageRetryFailed | SDWebImageLowPriority;// | SDWebImageAvoidAutoSetImage;
            [self sd_setImageWithURL:imgUrl placeholderImage:phImg?phImg:kImgPH options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                StrongSelf(self);
                if ((image == nil) || (error != nil)) {
                    return;
                }
                //下面这种方式会更好，可以解决滚动过快时，防止再赋值。其已经再次被复用时，不应该再赋值了
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                    StrongSelf(self);
                    //NSLog(@"<-- %s, %d --> 🐔%@🐔", __FUNCTION__, __LINE__, NSStringFromCGSize(resultSize));
                    @autoreleasepool {
                        // 将剪裁后的图片记录下来，下次直接使用
                        CGSize resultS = CGSizeMake(kImgScale(wh) * 0.8, kImgScale(wh) * 0.8);
                        UIImage *clipeImg = [image hyb_clipToSize:resultS isEqualScale:NO];
                        // 存储到本地，若开启了缓存到内存，则也一起缓存内存，以提高性能
                        NSString *cacheKey = [NSString stringWithFormat:@"%@&thumbnail%d", imageURL.absoluteString, (int)wh];
                        [HYBImageClipedManager storeClipedImage:clipeImg toDiskWithKey:cacheKey];
                        
                        #if 1   // 返回主线程显示图片
                        dispatch_async(dispatch_get_main_queue(), ^{
                            StrongSelf(self);
                            if ([[[self.imgThumbURL componentsSeparatedByString:@"&thumbnail"] safeObjectAtIndex:0] isEqualToString:imageURL.absoluteString]) {
                                self.image = clipeImg;
                            } else {
                                self.image = kImgPH;
                            }
                        });
                        #endif
                        
                    }
                });
            }];
        }
    }];
#endif
}

#pragma mark - ------------------ <#note#> ------------------
- (void)addTarget:(id)target action:(SEL)action {
    self.userInteractionEnabled = YES;
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];
    [self addGestureRecognizer:tap];
}

@end
